/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * <p>Project: app2022 - Nio6
 * <p>Powered by webrx On 2022-01-20 11:47:42
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Nio6 {
    public static void main(String[] args) throws IOException {
        //建立目录
        //Files.createDirectories(Paths.get("d:/abc/aaa"));

        //删除目录 只能删除(空目录)
        //Files.delete(Paths.get("d:/abc"));
        //Files.delete(Paths.get("d:/abc/aaa"));

        //遍历目录
        Path path = Paths.get(System.getProperty("user.dir"));
        var dirs = Files.newDirectoryStream(path);
        for (Path p : dirs) {
            System.out.print(p.getFileName());
            System.out.println(Files.isDirectory(p) ? "目录" : "文件");
        }

        //删除c:/aaa目录，不是空目录，使用递归方法
        deldir(Paths.get("c:\\aaa - 副本"));
    }

    /**
     * Description: nio删除非空目录
     *
     * @date: 2022/1/20 11:59
     * @params: [java.nio.file.Path]
     * @return: void
     */
    public static void deldir(Path path) {
        if (Files.isDirectory(path)) {
            try (var dirs = Files.newDirectoryStream(path)) {
                for (Path p : dirs) {
                    if (Files.isDirectory(p)) {
                        deldir(p);
                    } else {
                        Files.delete(p);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            Files.delete(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
